package cn.bidaround.point;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.telephony.TelephonyManager;


/**
 * 友推积分操作类
 * @author youtui
 * @since 14/6/19 
 */
public class YtPoint {
	/**服务器返回的Json字符串*/
	private static String jsonStr;	
	/**积分数组*/
	public static int[] pointArr = new int[ChannelId.CHANNEL_SIZE];
	/**SIM卡序列号*/
	private static String cardNum;
	/**手机imei*/
	private static String imei;
	/**获取积分监听*/
	private static YtPointListener listener;
	/**友推AppKey*/
	public static String youTui_AppKey; 
	private YtPoint() {
	}

	/** 未调用新线程 */
	public static void init(Context context,String youTui_AppKey) {
		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
		cardNum = tm.getSimSerialNumber();
		imei = tm.getDeviceId();
		YtPoint.youTui_AppKey = youTui_AppKey;
		YouTuiAcceptor.init(context, youTui_AppKey);
		//refresh(context,youTui_AppKey);
	}
	
	public static void setListener(YtPointListener listener){
		YtPoint.listener = listener;
	}

	/**
	 * 分享获得积分
	 * 
	 * @param context
	 * @param appId
	 * @param channelId
	 */
	public static void sharePoint(final Context context, final String appId, final int channelId, final String url, final boolean isShareContent, final String uniqueCode) {
		/** 异步操作获取积分 */
		new Thread() {
			public void run() {
				/** arr用来保存未分享时积分 */
				int[] arr = new int[pointArr.length];
				addArr(pointArr, arr);
				HttpClient client = new DefaultHttpClient();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				HttpPost post = new HttpPost(YoutuiConstants.YT_URL + "/activity/sharePoint");
				// 传入手机号，设备号，友推id,频道id
				params.add(new BasicNameValuePair("cardNum", cardNum));
				params.add(new BasicNameValuePair("imei", imei));
				params.add(new BasicNameValuePair("appId", appId));
				params.add(new BasicNameValuePair("channelId", String.valueOf(channelId)));
				// 用户分享的真实url
				params.add(new BasicNameValuePair("realUrl", url));
				// 传入唯一标示
				params.add(new BasicNameValuePair("virtualUrl", uniqueCode));
				// 是否为分享内容
				params.add(new BasicNameValuePair("shareContent", Boolean.toString(isShareContent)));
				// 是否为YOUTUI分享(可能为积分版本分享)
				params.add(new BasicNameValuePair("isYoutui", Boolean.toString(true)));
				params.add(new BasicNameValuePair("point", String.valueOf(pointArr[channelId])));

				try {
					post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					HttpResponse response = client.execute(post);
					parse(context,appId);
					if(listener!=null){
						listener.onSuccess(arr[channelId]-pointArr[channelId]);
					}
				} catch (ClientProtocolException e) {
					if(listener!=null){
						listener.onFail();
					}
					e.printStackTrace();
				} catch (IOException e) {
					if(listener!=null){
						listener.onFail();
					}
					e.printStackTrace();
				} catch (JSONException e) {
					if(listener!=null){
						listener.onFail();
					}
					YtLog.e("at YtPoint:", "获取积分失败,可能原因是网络连接失败或者该应用暂无积分活动");
					e.printStackTrace();
				}
			};
		}.start();

		/** 临时为兼职猫添加的活动 */

	}

	/**
	 * @param context
	 * @return 返回获取积分的Json字符串
	 */
	private static String getPointJson(Context context, String youTui_AppKey) {

		HttpParams httpParam = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParam, 10000);
		HttpClient client = new DefaultHttpClient(httpParam);
		HttpPost post = new HttpPost(YoutuiConstants.YT_URL + "/activity/sharePointRule");

		try {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("cardNum", cardNum));
			params.add(new BasicNameValuePair("imei", imei));
			params.add(new BasicNameValuePair("appId", youTui_AppKey));
			params.add(new BasicNameValuePair("phoneType", android.os.Build.MODEL));
			params.add(new BasicNameValuePair("sysVersion", android.os.Build.VERSION.RELEASE));
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));

			HttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			jsonStr = EntityUtils.toString(entity);
			YtLog.d("获取积分信息", jsonStr);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			jsonStr = null;
		} catch (IOException e) {
			e.printStackTrace();
			jsonStr = null;
		}
		return jsonStr;
	}

	/**
	 * 
	 * 解析平台积分并装入pointArr
	 * 
	 * @return
	 * @throws JSONException
	 */
	public static int[] parse(Context context,String appid) throws JSONException  {
		String str = getPointJson(context,appid);
		if (str != null) {
			// 获取成功的话，装入pointArr
			JSONObject objectJson = new JSONObject(str).getJSONObject("object");
			for (int i = 0; i < pointArr.length-1; i++) {
				pointArr[i] = objectJson.getInt("channel" + i);
			}
		} else {
			// 如果获取积分失败，pointArr都设置为0
			for (int i = 0; i < pointArr.length; i++) {
				pointArr[i] = 0;
			}
		}
		return pointArr;
	}

	/**
	 * 刷新积分
	 */
	public static void refresh(Context context,String appid) {
		try {
			parse(context,appid);
		} catch (JSONException e) {
			YtLog.e("at YtPoint:", "获取积分失败,可能原因是网络连接失败或者该应用暂无积分活动");
			//e.printStackTrace();
		}
	}


	/**
	 * 获得各平台积分的数组
	 * 
	 * @return
	 */
	public int[] getPoint() {
		return pointArr;
	}
	
	/**
	 * 获取指定平台积分
	 * @param channelId
	 * @return 指定平台积分
	 */
	public static int getPlatformPoint(int channelId){
		return pointArr[channelId];
	}

	/**
	 * 判断是否有积分活动
	 * 
	 * @return 是否有积分活动
	 */
	public static boolean hasPoint() {
		for (int i : pointArr) {
			if (i > 0) {
				return true;
			}
		}
		return false;
	}
	
	/**将一个数组的元素填充到另一个数组用来保存元素信息*/
	public static void addArr(int[] fromArr, int[] toArr) {
		for (int i = 0; i < toArr.length; i++) {
			toArr[i] = fromArr[i];
		}
	}
	
	/**
	 * 释放listener
	 */
	public static void release(final Context context){
		listener = null;
		new Thread(){
			public void run() {
				YouTuiAcceptor.close(context, youTui_AppKey);
			};
		}.start();
		
	}
}
